package com.wtwd.campus.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.DynamicParameter;
import com.github.xiaoymin.knife4j.annotations.DynamicParameters;
import com.wtwd.campus.annotation.AuditLog;
import com.wtwd.campus.common.RespCode;
import com.wtwd.campus.entity.Classes;
import com.wtwd.campus.entity.School;
import com.wtwd.campus.entity.SysUser;
import com.wtwd.campus.model.ClassQueryModel;
import com.wtwd.campus.model.vo.ClassesVO;
import com.wtwd.campus.model.vo.PageDataVO;
import com.wtwd.campus.model.vo.ResultVO;
import com.wtwd.campus.service.ClassService;
import com.wtwd.campus.service.LogService;
import com.wtwd.campus.service.SchoolService;
import com.wtwd.campus.service.SysUserService;
import com.wtwd.campus.utils.AuditLogUtils;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zdl
 * @since 2021-06-30
 */
@Api(tags = "班级管理")
@RestController
@RequestMapping("/class")
public class ClassController {
    @Resource
    private ClassService classService;

    @Resource
    private SysUserService sysUserService;

    @Resource
    private SchoolService schoolService;

    @Autowired
    private LogService logService;

    @ApiOperation(value = "查询班级分页数据", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo", value = "页数", required = true, dataTypeClass = Integer.class)
            , @ApiImplicitParam(name = "pageSize", value = "页大小", required = true, dataTypeClass = Integer.class)
    })
    @GetMapping("/page")
    public ResultVO<PageDataVO<ClassesVO>> queryPage(@RequestParam(defaultValue = "1") Integer pageNo
            , @RequestParam(defaultValue = "10") Integer pageSize, ClassQueryModel classQueryModel) {
        Page<ClassesVO> page = new Page<>(pageNo, pageSize);
        SysUser user = sysUserService.getCurrentLoginUser();
        List<Integer> schoolIds = null;
        Integer schoolId = classQueryModel.getSchoolId();
        if (schoolId == null) {
            List<School> schools = schoolService.getSchoolByOrgCode(user.getOrgCode());
            schoolIds = schools.stream().map(School::getId).collect(Collectors.toList());
        } else {
            schoolIds = new ArrayList<>();
            schoolIds.add(schoolId);
        }
        classQueryModel.setSchoolIds(schoolIds);
        IPage<ClassesVO> dataPage = classService.queryPage(page, classQueryModel);

        Map<Integer, String> schoolNames = schoolService.getSchoolNamesBySchoolIds(StringUtils.join(schoolIds, ','));
        dataPage.getRecords().forEach(item -> {
            item.setSchoolName(schoolNames.get(item.getSchoolId()));
        });
        return ResultVO.ok(dataPage);
    }

    @ApiOperation("添加班级信息")
    @DynamicParameters(name = "addClassModel", properties = {
            @DynamicParameter(name = "schoolId", value = "学校ID", dataTypeClass = Integer.class, required = true)
            , @DynamicParameter(name = "classesName", value = "班级名称", dataTypeClass = String.class, required = true)
            , @DynamicParameter(name = "gradeId", value = "年级ID", dataTypeClass = Integer.class, required = true)
    })
    @ApiResponses({@ApiResponse(code = 1013, message = "该班级已存在")})
    @PostMapping("/classInfo")
    @AuditLog(operationType = "添加班级", operationContent = "", orgCode = "")
    public ResultVO add(@RequestBody JSONObject addClassModel) {
        Classes classes = JSONObject.toJavaObject(addClassModel, Classes.class);
        ResultVO resultVO = classService.createClass(classes);
        if (resultVO.getCode() == RespCode.SUCCESS.getCode()) {
            Method method = null;
            try {
                method = ClassController.class.getMethod("add", JSONObject.class);
                //获取操作的组织的code
                Integer schoolId = (Integer) addClassModel.get("schoolId");
                School school = logService.getSchoolById(schoolId);
                String orgCode = school.getOrgCode();
                String operationContent = "新增班级：".concat(classes.getClassesName());
                AuditLogUtils.modifyAnnotation(method, operationContent, orgCode);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
        return resultVO;
    }


    @ApiOperation("更新班级信息")
    @DynamicParameters(name = "updateClassModel", properties = {
            @DynamicParameter(name = "classesId", value = "班级ID", dataTypeClass = Integer.class, required = true)
            , @DynamicParameter(name = "classesName", value = "班级名称", dataTypeClass = String.class)
            , @DynamicParameter(name = "gradeId", value = "年级ID", dataTypeClass = Integer.class)
    })
    @ApiResponses({@ApiResponse(code = 1013, message = "该班级已存在")})
    @PutMapping("/classInfo")
    @AuditLog(operationType = "更新班级信息", operationContent = "", orgCode = "")
    public ResultVO update(@RequestBody JSONObject updateClassModel) {
        Classes classes = JSONObject.toJavaObject(updateClassModel, Classes.class);
        //根据班级id获取班级信息以及所属学校组织code
        Map<String, Object> map = logService.getClassMessAndSchoolCodeById(classes.getClassesId());
        String className2 = (String) map.get("classes_name");
        String orgCode = (String) map.get("org_code");
        ResultVO resultVO = classService.updateClass(classes);
        if (resultVO.getCode() == RespCode.SUCCESS.getCode()) {
            Method method = null;
            try {
                method = ClassController.class.getMethod("update", JSONObject.class);
                String operationContent = "";
                if (!classes.getClassesName().equals(className2)) {
                    operationContent = classes.getClassesName().concat("更改为：").concat(className2);
                } else {
                    operationContent = "修改班级信息：".concat(classes.getClassesName());
                }
                AuditLogUtils.modifyAnnotation(method, operationContent, orgCode);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
        return resultVO;
    }

    @ApiOperation("删除班级信息")
    @ApiImplicitParam(name = "id", value = "班级id", required = true, dataTypeClass = Integer.class, paramType = "path")
    @ApiResponses({@ApiResponse(code = 1012, message = "该班级存在教师")})
    @DeleteMapping("/classInfo/{id}")
    @AuditLog(operationType = "删除班级信息", operationContent = "", orgCode = "")
    public ResultVO delete(@PathVariable Integer id) {
        //根据班级id获取班级信息以及所属学校组织code
        Map<String, Object> map = logService.getClassMessAndSchoolCodeById(id);
        String className = (String) map.get("classes_name");
        String orgCode = (String) map.get("org_code");
        ResultVO resultVO = classService.deleteClassesById(id);
        if (resultVO.getCode() == RespCode.SUCCESS.getCode()) {
            Method method = null;
            try {
                method = ClassController.class.getMethod("delete", Integer.class);
                String operationContent = "删除班级:".concat(className);
                AuditLogUtils.modifyAnnotation(method, operationContent, orgCode);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
        return resultVO;
    }

}

